"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 配置文件权限异常恢复，执行数据恢复
Create At   : 2020/07/27
@zou_jialiang0505328126
Description :
    1. 执行gs_dump，导出postgres数据库全量信息
    2. 修改配置文件权限为不可读不可写
    3. 连接数据库
    4. 运行tpcc指令
    5. 恢复配置文件权限
    6. 连接数据库
    7. 数据恢复
    8. 运行tpcc指令
Expect      :
    1. 返回信息：
    2. 执行成功，无返回信息
    3. 非socket连接连接成功：postgres=>
    4. 运行正常，返回信息中关注
    5. 执行成功，无返回信息
    6. 非socket连接连接成功：postgres=>
    7. 返回信息
    8. 返回信息关注
History     :
    modified: 2020/12/09  modified by @wan005,修改恢复数据库为新创建数据库，防止恢复失败导致后续用例失败
    modified: 2021/1/9  modified by @peilinqian,修改建库语句，以防出现存在该库导致校验失败问题
"""
import os
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()


class Stop_immediate(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    file_path = ''
    conffile_name = os.path.join(macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME)
    primary_sh = CommonSH('PrimaryDbUser')
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby2DbUser')
    dump_file_name = 'test_pid.tar'

    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info('------------Opengauss_Reliability_Dbsys_Case174.py start------------')
        self.Constant = Constant()
        logger.info("----------------------get socket file path--------------")
        sql = "show unix_socket_directory"
        getfilepath_msg = self.primary_sh.executDbSql(sql)
        logger.info(getfilepath_msg)
        self.file_path = getfilepath_msg.split('\n')[2]
        logger.info(self.file_path)

        self.dbname = 'dbsys_case174_db'
        logger.info("---------------------create database--------------------")
        result = self.primary_sh.executDbSql(f'drop database if exists {self.dbname};create database { self.dbname};')
        logger.info(result)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS_MSG, result)

    def test_stop_immediate(self):
        logger.info('--------------------dump file-------------------------')
        time.sleep(30)
        dump_msg = self.primary_sh.dumpFile(os.path.join(macro.DB_INSTANCE_PATH, self.dump_file_name))
        logger.info(dump_msg)
        flag = 'dump database ' + self.dbPrimaryUserNode.db_name + ' successfully'
        self.assertIn(flag, dump_msg)

        logger.info("------------------modify conffile permission----------------------")
        delete_cmd = f'chmod 000 {self.conffile_name}'
        self.dbPrimaryRootNode.sh(delete_cmd).result()
        logger.info(delete_cmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(self.file_path)
        logger.info(socket_connect_msg)
        self.assertEqual(socket_connect_msg, '')

        logger.info("---------------------start TPCC----------------------")
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, macro.TPCC_PATH)
        logger.info('-------------' + tpcc_result + '-----------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.Constant.TPCC_SUCCESS_MSG) > -1)

        logger.info("------------------------recover conf file------------------")
        recover_cmd = f'chmod 700 {self.conffile_name}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(self.file_path)
        logger.info(socket_connect_msg)
        logger.info(type(socket_connect_msg))
        self.assertEqual(socket_connect_msg, '')

        logger.info('--------------------restore file-------------------------')
        dump_msg = self.primary_sh.restoreFile(os.path.join(macro.DB_INSTANCE_PATH, self.dump_file_name),
                                               get_detail=True, dbname=self.dbname)
        logger.info(dump_msg)
        self.assertTrue(dump_msg.find(self.Constant.RESTORE_SUCCESS_MSG) > -1)

        logger.info("---------------------start TPCC----------------------")
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, macro.TPCC_PATH)
        logger.info('-------------' + tpcc_result + '-----------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.Constant.TPCC_SUCCESS_MSG) > -1)

        # 校验刷脏页是否完成
        logger.info('校验刷脏页是否完成')
        dirty_page_finshed_flag = self.primary_sh.check_whether_remain_dirty_page()
        self.assertTrue(dirty_page_finshed_flag)

        # 校验备机是否完成数据同步
        logger.info('校验备机是否完成数据同步')
        flag_1 = self.standby_1_sh.check_data_consistency()
        self.assertTrue(flag_1)
        flag_2 = self.standby_2_sh.check_data_consistency()
        self.assertTrue(flag_2)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("------------------------recover conf file------------------")
        recover_cmd = f'chmod 700 {self.conffile_name}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        logger.info("------------------------delete dump file------------------")
        recover_cmd = f'rm -rf ' \
            f'{os.path.join(macro.DB_INSTANCE_PATH, self.dump_file_name)}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        logger.info("---------------------drop database--------------------")
        result = self.primary_sh.executDbSql(f'drop database {self.dbname};')
        logger.info(result)
